<script lang="ts" setup>
import type {
  GridInstance as VxeGridInstance,
  VxeGridListeners,
  VxeGridProps,
} from '#/adapter/vxe-table';
import type { PartnershipInfo } from '#/api/core/hhr';

import { computed, onMounted, ref } from 'vue';

import { Button, Form, Input, message, Modal } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { approvePartnershipApi, getPartnershipListApi } from '#/api/core/hhr';

// 表格引用
const gridRef = ref<VxeGridInstance>();

// 存储表格数据
const tableData = ref<PartnershipInfo[]>([]);

// 添加审批相关的状态
const showApprovalModal = ref(false);
const currentRecord = ref<null | PartnershipInfo>(null);
const approvalComment = ref('');
const approvalLoading = ref(false);

// 添加分页相关的 ref
const currentPage = ref(1);
const totalPage = ref(0);

// 表格配置
const gridOptions = computed<VxeGridProps<PartnershipInfo>>(() => ({
  columns: [
    { field: 'id', title: 'ID', width: 80 },
    { field: 'username', title: '用户名', width: 120 },
    { field: 'phone', title: '手机号', width: 120 },
    { field: 'wechat', title: '微信号', width: 120 },
    { field: 'status', title: '状态', width: 100 },
    {
      field: 'apply_time',
      title: '申请时间',
      width: 180,
      formatter: ({ cellValue }) => {
        if (!cellValue) return '';
        return new Date(cellValue).toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit',
          hour12: false,
        });
      },
    },
    { field: 'comment', title: '备注', minWidth: 200 },
    {
      title: '操作',
      width: 120,
      slots: {
        default: 'operate',
      },
    },
  ],
  data: tableData.value,
  pagerConfig: {
    enabled: true,
    pageSize: 10,
    total: totalPage.value * 10,
    currentPage: currentPage.value,
    layouts: ['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Total'],
    perfect: true,
  },
  sortConfig: {
    multiple: true,
  },
}));

const gridEvents: VxeGridListeners<PartnershipInfo> = {
  pageChange: ({ currentPage: newPage }) => {
    currentPage.value = newPage;
    loadData();
  },
};

const [Grid, gridApi] = useVbenVxeGrid({
  gridEvents,
  gridOptions: gridOptions.value,
});

// 定义搜索表单的数据结构
interface SearchForm {
  username: string;
}

// 搜索表单数据
const searchForm = ref<SearchForm>({
  username: '',
});

// 修改加载数据方法
async function loadData() {
  try {
    gridApi.setLoading(true);
    const params = {
      current_page: currentPage.value,
      username: searchForm.value.username,
    };
    const data = await getPartnershipListApi(params);

    if (Array.isArray(data) && data.length > 0) {
      tableData.value = data;
      const total_page = data[0]?.total_page || 0;
      totalPage.value = total_page;

      gridApi.setGridOptions({
        data: tableData.value,
        pagerConfig: {
          ...gridOptions.value.pagerConfig,
          total: total_page * 10,
          currentPage: currentPage.value,
        },
      });
    } else {
      tableData.value = [];
    }
  } catch {
    tableData.value = [];
  } finally {
    gridApi.setLoading(false);
  }
}

// 搜索方法
function handleSearch() {
  loadData();
}

// 重置搜索条件
function handleReset() {
  searchForm.value = {
    username: '',
  };
  loadData();
}

onMounted(() => {
  loadData();
});

// 表格显示控制
const showBorder = gridApi.useStore((state) => state.gridOptions?.border);
const showStripe = gridApi.useStore((state) => state.gridOptions?.stripe);

function changeBorder() {
  gridApi.setGridOptions({
    border: !showBorder.value,
  });
}

function changeStripe() {
  gridApi.setGridOptions({
    stripe: !showStripe.value,
  });
}

// 处理审批点击
function handleApprove(row: PartnershipInfo) {
  currentRecord.value = row;
  approvalComment.value = '';
  showApprovalModal.value = true;
}

// 提交审批
async function submitApproval(status: number) {
  if (!currentRecord.value) return;

  try {
    approvalLoading.value = true;
    await approvePartnershipApi({
      id: currentRecord.value.id,
      status,
      comment: approvalComment.value,
    });

    message.success('审批成功');
    showApprovalModal.value = false;
    loadData(); // 重新加载列表
  } catch {
    message.error('审批失败');
  } finally {
    approvalLoading.value = false;
  }
}
</script>

<template>
  <div class="p-4">
    <!-- 简化搜索表单 -->
    <Form class="mb-4" layout="inline">
      <Form.Item label="用户名">
        <Input
          v-model:value="searchForm.username"
          allow-clear
          placeholder="请输入用户名"
        />
      </Form.Item>
      <Form.Item>
        <Button class="mr-2" type="primary" @click="handleSearch">搜索</Button>
        <Button @click="handleReset">重置</Button>
      </Form.Item>
    </Form>

    <div class="vp-raw w-full">
      <Grid ref="gridRef">
        <template #operate="{ row }">
          <Button
            v-if="row.status === '待处理'"
            size="small"
            type="primary"
            @click="handleApprove(row)"
          >
            审批
          </Button>
        </template>

        <template #toolbar-tools>
          <Button class="mr-2" type="primary" @click="changeBorder">
            {{ showBorder ? '隐藏' : '显示' }}边框
          </Button>
          <Button class="mr-2" type="primary" @click="changeStripe">
            {{ showStripe ? '隐藏' : '显示' }}斑马纹
          </Button>
        </template>
      </Grid>
    </div>

    <!-- 添加审批弹窗 -->
    <Modal
      v-model:visible="showApprovalModal"
      :footer="null"
      title="合伙人申请审批"
      @ok="() => {}"
    >
      <Form layout="vertical">
        <Form.Item label="申请人">
          <Input :value="currentRecord?.username" readonly />
        </Form.Item>
        <Form.Item label="审批意见">
          <Input.TextArea
            v-model:value="approvalComment"
            :rows="4"
            placeholder="请输入审批意见"
          />
        </Form.Item>
        <Form.Item class="text-right">
          <Button
            :loading="approvalLoading"
            class="mr-2"
            @click="showApprovalModal = false"
          >
            取消
          </Button>
      
          <Button
            :loading="approvalLoading"
            type="primary"
            @click="submitApproval(1)"
          >
            通过
          </Button>
        </Form.Item>
      </Form>
    </Modal>
  </div>
</template>
